﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using YT.Commons;
using YT.Modules;
using YT.DB;

namespace YT.XH.NOSE
{
    public partial class frmNSMethodMtn_Add : Form
    {
        private string mstrSickRecID = string.Empty;
        private string mstrCaseName = string.Empty;
        private DBAccess mdbcon = new DBAccess(false, false);
        private bool blnExit = false;

        private struct SickInfo
        {
            public string strSickRecID;
            public string strSickName ;
            public string strMobilePhone ;
        }

        public frmNSMethodMtn_Add()
        {
            InitializeComponent();
        }

        public frmNSMethodMtn_Add(string strSickRecID,string strCaseName)
        {
            InitializeComponent();
            mstrSickRecID = strSickRecID;
            mstrCaseName = strCaseName;
        }

        private bool ValidCheck()
        {
            if (this.dgvDtl.CurrentRow.Cells[colName.Index].Value == "")
            {
                MessageBox.Show("治疗名称不能为空.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (  CvtFunc.ToInt ( this.dgvDtl.CurrentRow.Cells[colVisit.Index].Value) == 0 )
            {
                MessageBox.Show("回访周期不能为空并且要大于0.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if ( this.dgvDtl.CurrentRow.Cells[colVisit.Index].Value == "")
            {
                MessageBox.Show("回访周期 单位 不能为空.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }


        private void FillGrid()
        {
            string strSQL = string.Empty;
            strSQL = " select * from NoseVisitWeek_Add where SickRecID='"+ mstrSickRecID  +"'  order by recid ";
            DataTable dtVisit = mdbcon.GetDataTable(strSQL);
            if (dtVisit.Rows.Count == 0)
            {
                this.dgvDtl.Rows.Add();
                this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colName.Index].Value = mstrCaseName;
            }
            else
            {
                foreach (DataRow drRow in dtVisit.Rows)
                {
                    this.dgvDtl.Rows.Add();
                    this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colName.Index].Value = CvtFunc.ToString(drRow["CaseName"]);
                    this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colVisit.Index].Value = CvtFunc.ToString(drRow["VisitTimes"]);
                    this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colUnit.Index].Value = CvtFunc.ToString(drRow["VisitUnit"]);
                    this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colTotalTimes.Index].Value = CvtFunc.ToString(drRow["TotalTimes"]);
                    this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colRecID.Index].Value = CvtFunc.ToString(drRow["RecID"]);
                }
                this.dgvDtl.RefreshEdit();
            }
        }

        private void frmNSMethodMtn_Add_Load(object sender, EventArgs e)
        {
            this.Text = "添加回访";
            FillGrid();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            UpdateData();
        }

        private bool CheckData(  DataGridViewRow dgvRow  )
        {
            if (CvtFunc.ToString(dgvRow.Cells[colTotalTimes.Index].Value) == "" || CvtFunc.ToInt(dgvRow.Cells[colTotalTimes.Index].Value) <= 0 )
            {
                MessageBox.Show ( "回访次数不能为空或小于等于0！", "", MessageBoxButtons.OK , MessageBoxIcon.Warning );
                return false;
            }
            else if (CvtFunc.ToString(dgvRow.Cells[colVisit.Index].Value) == "" || CvtFunc.ToInt(dgvRow.Cells[colVisit.Index].Value) <= 0)
            {
                MessageBox.Show("回访周期不能为空或小于等于0！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (CvtFunc.ToString(dgvRow.Cells[colUnit.Index].Value) == "")
            {
                MessageBox.Show("回访周期的单位不能为空！", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }


        private bool UpdateData()
        {
            this.dgvDtl.EndEdit();
            string strSQL = string.Empty;
            foreach (DataGridViewRow dgvRow in this.dgvDtl.Rows)
            {
                if (!CheckData( dgvRow  )) return false;
            }

            foreach (DataGridViewRow dgvRow in this.dgvDtl.Rows)
            {
                DateTime datLastSendDate = DateTime.Now.Date;
                strSQL = "select max(SendDate) as SendDate from SmsOutbox where sickrecid='" + mstrSickRecID + "' ";
                DataRow drLastDate = mdbcon.GetDataFirstRow(strSQL);
                if (drLastDate != null)
                {
                    datLastSendDate = CvtFunc.ToDateTime(drLastDate["SendDate"]);
                    if (datLastSendDate.CompareTo(DateTime.Now.Date) < 0)
                    {
                        datLastSendDate = DateTime.Now;
                    }
                }
                else
                {
                    datLastSendDate = DateTime.Now;
                }

                if (CvtFunc.ToDouble(dgvRow.Cells[colRecID.Index].Value) > 0)
                {
                    string strRecID = CvtFunc.ToString(dgvRow.Cells[colRecID.Index].Value);
                    if (CvtFunc.ToDouble(dgvRow.Cells[colRecID.Index].Value) > 0)
                    {
                        
                            strSQL = "delete from SmsOutbox where SickRecID='" + mstrSickRecID + "' and AddRecID='" + strRecID + "'";
                            mdbcon.ExecuteSql(strSQL);
                        
                    }
                    UpdateMsg(dgvRow, datLastSendDate);
                }
                else
                {
                    

                    strSQL = @" insert into NoseVisitWeek_Add (SickRecID, casename,visittimes,visitunit,totaltimes) 
                            values ('{0}','{1}','{2}','{3}','{4}');;Select @@identity";
                    strSQL = string.Format ( strSQL, mstrSickRecID ,CvtFunc.ToString ( dgvRow.Cells [colName.Index].Value )
                                                                   ,CvtFunc.ToString ( dgvRow.Cells [colVisit.Index ].Value )
                                                                   ,CvtFunc.ToString ( dgvRow.Cells [colUnit .Index ].Value )
                                                                   ,CvtFunc.ToString ( dgvRow.Cells [colTotalTimes.Index ].Value )
                                                                   );
                    DataRow drAdd = mdbcon.GetDataFirstRow(strSQL);
                    dgvRow.Cells[colRecID.Index].Value = CvtFunc.ToString(drAdd[0]);
                    UpdateMsg( dgvRow, datLastSendDate  );
                }
            }
            return true;
        }


        private bool UpdateMsg( DataGridViewRow dgvRow, DateTime  datLastSendDate )
        {
        
            int intSendTimes = 1;
            int intTotalMsg = CvtFunc.ToInt ( dgvRow.Cells[colTotalTimes.Index].Value ); 
            SickInfo sickinfo = new SickInfo();
            string strSQL = "select * from mSickPerson where SickRecID='"+ mstrSickRecID +"'";
            DataRow drSickInfo = mdbcon.GetDataFirstRow ( strSQL );
            bool blnNeedMsg = true;
            if (!CvtFunc.ToBoolean(DataFunctions.GetFieldValue("mSickPerson", "NeedMsg", "sickrecid='" + mstrSickRecID + "'")))
            {
                MessageBox.Show("不能对此患者发送短信息。", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                blnNeedMsg = false;
            }
            if (drSickInfo != null)
            {
                sickinfo.strSickName = CvtFunc.ToString(drSickInfo["SickName"]);
                sickinfo.strMobilePhone = CvtFunc.ToString(drSickInfo["MobilePhone"]);
                sickinfo.strSickRecID = mstrSickRecID;

                string strMsg = DataFunctions.GetFieldValue("mSmsMessage", "SmsMessage", "Type='N'");
                int intSplitDay = 0;

                for (int intRow = 0; intRow <1; intRow++)
                {
                    if (CvtFunc.ToString(dgvRow.Cells[colUnit.Index].Value) == "天")
                    {
                        int intVisit = CvtFunc.ToInt(dgvRow.Cells[colVisit.Index].Value);
                        if (intVisit > 0) intSplitDay = CvtFunc.ToInt(intVisit);
                        for (int i = 0; i < intTotalMsg; i++)
                        {
                            DateTime datSendDate = datLastSendDate.AddDays(CvtFunc.ToDouble(intSplitDay * intSendTimes));
                            if (blnNeedMsg) InsertMsgIntoSmsOutmsg(sickinfo, datSendDate, strMsg, dgvRow);
                            intSendTimes++;
                            //if (intSendTimes > intTotalMsg) break;
                        }
                    }
                    else if (CvtFunc.ToString(dgvRow.Cells[colUnit.Index].Value) == "周")
                    {
                        int intVisit = CvtFunc.ToInt(dgvRow.Cells[colVisit.Index].Value);
                        if (intVisit > 0) intSplitDay = CvtFunc.ToInt(7.00*intVisit);
                        for (int i = 0; i < intTotalMsg; i++)
                        {
                            DateTime datSendDate = datLastSendDate.AddDays(CvtFunc.ToDouble(intSplitDay * intSendTimes));
                            if (blnNeedMsg) InsertMsgIntoSmsOutmsg(sickinfo, datSendDate, strMsg, dgvRow);
                            intSendTimes++;
                            //if (intSendTimes > intTotalMsg) break;
                        }
                    }
                    else if (CvtFunc.ToString(dgvRow.Cells[colUnit.Index].Value) == "月")
                    {
                        int intVisit = CvtFunc.ToInt(dgvRow.Cells[colVisit.Index].Value);
                        if (intVisit > 0) intSplitDay = CvtFunc.ToInt(intVisit);
                        for (int i = 0; i < intTotalMsg; i++)
                        {
                            DateTime datSendDate = datLastSendDate.AddMonths(CvtFunc.ToInt (intSplitDay * intSendTimes));
                            if (blnNeedMsg) InsertMsgIntoSmsOutmsg(sickinfo, datSendDate, strMsg, dgvRow);
                            intSendTimes++;
                            //if (intSendTimes > intTotalMsg) break;
                        }
                    }                    
                }
            }
            return true;
        }

        private bool InsertMsgIntoSmsOutmsg( SickInfo sickinfo, DateTime datSendDate, string strMsg,DataGridViewRow dgvRow )
        {
            System.Threading.Thread.Sleep(1000);
            string strSQL = @" Insert into SmsOutbox (SickName,SickRecID,MobilePhone,Message,SendDate,AddRecID,MsgType)
                                VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}') ";
            strSQL = string.Format(strSQL, sickinfo.strSickName
                                            , sickinfo.strSickRecID
                                            , sickinfo.strMobilePhone
                                            , strMsg
                                            , datSendDate
                                            , CvtFunc.ToString ( dgvRow.Cells[colRecID.Index].Value   )
                                            , 'N');
            mdbcon.ExecuteSql(strSQL);
            return true;

        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            this.dgvDtl.EndEdit();
           
                this.dgvDtl.Rows.Add();
                this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colName.Index].Value = mstrCaseName;
                this.dgvDtl.CurrentCell = this.dgvDtl.Rows[this.dgvDtl.Rows.Count - 1].Cells[colName.Index];    
        }

        private void dgvDtl_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (!ValidCheck()) e.Cancel = true ;

        }

        private void frmNSMethodMtn_Add_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否保存？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                UpdateData();
            }
        }

        private void dgvDtl_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string strSQL ="";
            if (this.dgvDtl.CurrentRow == null) return;
            if (CvtFunc.ToDouble(this.dgvDtl.Rows[e.RowIndex].Cells[colRecID.Index].Value) <= 0)
            {
                if (e.ColumnIndex == colDel.Index)
                {
                    this.dgvDtl.Rows.RemoveAt(e.RowIndex);
                }
            }
            else
            {
                if (e.ColumnIndex == colDel.Index)
                {
                    if (this.dgvDtl.CurrentRow.Index == this.dgvDtl.Rows.Count - 1)
                    {
                        if (this.dgvDtl.Rows[e.RowIndex] != null)
                        {
                            string strRecID = CvtFunc.ToString(this.dgvDtl.CurrentRow.Cells[colRecID.Index].Value);
                            if (CvtFunc.ToDouble(this.dgvDtl.Rows[e.RowIndex].Cells[colRecID.Index].Value) > 0)
                            {
                                if (MessageBox.Show("你是否删除此患者的未发送的信息？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                                {
                                    strSQL = "delete from SmsOutbox where SickRecID='" + mstrSickRecID + "' and AddRecID='" + strRecID + "'";
                                    mdbcon.ExecuteSql(strSQL);
                                }
                            }                           
                            strSQL = "Delete NoseVisitWeek_Add where RecID='" + strRecID + "'";
                            mdbcon.ExecuteSql(strSQL);
                            this.dgvDtl.Rows.RemoveAt(e.RowIndex);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("只能删除最后一行。", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
    }
}
